//
//  WBUserAccountViewModel.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/15.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBUserAccountViewModel: NSObject {

    //视图模型需要引用模型对象--->处理数据逻辑
    var userAccount:WBUserAccount?
    
    //判断用户是否登录
    //计算型属性
    var userLogin:Bool{
        //需要满足以下条件
        if userAccount?.access_token != nil && isExpires == false {
            return true
        }
        return false
    }
    
    //判断令牌是否过期
    var isExpires:Bool{
        //过期日子比当前日期要大就没有过期
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            return false
        }
        return true
    }
    
    //单例对象,全局只有一个登陆的用户
    static let shared : WBUserAccountViewModel = WBUserAccountViewModel()
    
    
    //在用户已经登录的情况下给模型赋值
    override init() {
        super.init()
        userAccount = self.loadUserAccount()
    }
    
    //用户url头像
    var hearurl : URL? {
        return URL(string: userAccount?.avatar_large ?? "")
    }
    
    var access_token : String? {
        return userAccount?.access_token
    }
    
    
    //获取用户token
     func loadAccessToken(code : String,finished:@escaping (Bool)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //参数以字典的形式给
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (responsObject, error) in
            if error != nil{
                SVProgressHUD.showError(withStatus: "你这个菜逼,没网还玩个蛋蛋")
                return
            }
            //请求成功
//            print(responsObject)
            //使用access_token和uid来请求用户信息
            self.loadUserInfo(dict:responsObject as! [String : Any],loadUserInfoFinished:finished)
        }
    }
    
    //使用access_token和uid来请求用户信息
    private func loadUserInfo(dict:[String : Any],loadUserInfoFinished:@escaping (Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]
        //用惊叹号的原因 文档中:参数uid与screen_name二者必选其一，且只能选其一(http://open.weibo.com/wiki/2/users/show)
        let uid = dict["uid"]!
        let parameters = ["access_token":token,"uid":uid]
        
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "你这个菜逼,没网还玩个蛋蛋")
                return
            }
            
            //print(responseObject)  //将此数据挑选有效信息存放在模型中
            //将用户信息存储在本地
            //将授权之后的得到的字典和用户信息字典合并之后再存储
            //授权之后得到的字典
            var userInfoDict = responseObject as! [String : Any]
            for(key,value) in dict{
                userInfoDict[key] = value
            }
            
            //字典转模型
            let userAccount = WBUserAccount(dict: userInfoDict)
            //            print(userAccount)
            //存储模型对象到沙盒中Document目录下
            self.saveUserAccount(userAccount: userAccount)
            
            //如果不写首次登陆会有bug
            self.userAccount = userAccount
            
            //执行成功的回调
            loadUserInfoFinished(true)
            
        }
    }
    //存储模型对象,因此要传入参数模型
    private func saveUserAccount(userAccount:WBUserAccount){
        //存储模型,模型里要遵守NSCoding协议,实现协议方法
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: oauthpath)
        
        
    }
    //解档的时候有返回值,返回用户信息模型,?是因为当第一次的时候用户并没有登陆过并没有存储的信息
    private func loadUserAccount()->(WBUserAccount?){
//        print(path)
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: oauthpath)
        if let userAccount = account as? WBUserAccount{
            return userAccount
        }
        return nil
    }

    
}
